package com.xindacloud.sms.adapter.config;


import com.google.gson.Gson;
import com.xindacloud.sms.adapter.entity.SmsUser;
import com.xindacloud.sms.adapter.service.business.ISmsUserService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Slf4j
public class AuthIntercept implements HandlerInterceptor {

    @Autowired
    ISmsUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        final String internalInvokeAllow = req.getHeader("Internal-Invoke-Allow");
        if (StringUtils.isNotEmpty(internalInvokeAllow)) {
            if (Boolean.valueOf(internalInvokeAllow)) {
                return true;
            }
        }
        final String username = req.getHeader("username");
        final String password = req.getHeader("password");
        if (StringUtils.isEmpty(username)) {
            response(resp, "Bad Credentials");
            //throw new ServiceException("无效请求,[缺少token].", UnionResultHelp.StatusEnum.FailToken.code());
            return false;
        }
        if (StringUtils.isEmpty(password)) {
            response(resp, "Bad Credentials");
            //throw new ServiceException("无效请求,[缺少password].", UnionResultHelp.StatusEnum.FailToken.code());
            return false;
        }
        final SmsUser smsUser = userService.queryUserInfoFor(username, password);
        if (Objects.isNull(smsUser)) {
            response(resp, "Bad Credentials");
            //throw new ServiceException("无效请求,[无效的token,password].", UnionResultHelp.StatusEnum.FailToken.code());
            return false;
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private void response(HttpServletResponse resp, String content) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        resp.setStatus(200);
        resp.getWriter().write(new Gson().toJson(new UnionResultHelp(UnionResultHelp.StatusEnum.FailToken, content)));
    }

    private String getBasepath(HttpServletRequest req) {

        return req.getScheme() + "://"
                + req.getServerName() + ":"
                + req.getServerPort() + req.getContextPath();
    }

}
